'''
Author: @zhyy
Date: 2021-02-09 16:13:15
LastEditors: @zhyy
LastEditTime: 2021-02-09 18:29:57
'''
import time,sys,os,uuid,json,re
from app import db
from flask import request, jsonify,current_app,g
from app.models.model import User,Role
from app.func import error_code as RET
from app.validators.token import generate_token
from app.cache.redis_cache import db_cache,token_cache,uname_cache
from app.dao.db_query import DBQuery


# 邮箱注册
def register_by_email():
    # 接受的数据格式{"name":"",...}
    user_data = request.get_json()
    # print(user_data)
    name = user_data.get("name")
    email = user_data.get("email")
    password = user_data.get("password")
    password2 = user_data.get("password2")
    if not all([password, password2, email]):
        return jsonify({'code': 1001, "msg": "参数不完整"})
    if name and not re.match("\w{6,18}", name):
        return jsonify({'code': 1003, "msg": "用户名输入不合法，请重新输入"})
    if not name:
        name=uname_cache.rpop("username_list")
    if password != password2:
        return jsonify({'code': 1003, "msg": "两次密码不一致"})
    user=DBQuery.get_id(field=User.id,filters={User.email==email})
    if user:
        return jsonify({"code": 1004, 'msg': '用户已存在'})
    try:
        user = User.query.filter_by(email=email).first()
    except:
         return jsonify({"code": 5001, 'msg': '数据库查询错误'})
    if user:
        return jsonify({"code": 1004, 'msg': "邮箱已注册"})
    try:
        user = User(name=name, password=password, email=email)
        db.session.add(user)
        db.session.commit()
    except:
        db.session.rollback()
        return jsonify({'code': 5001, 'msg': "数据库错误"})
    return jsonify({'code': 200, 'msg': "注册成功"})

# 手机注册
def register_by_phone():
    if request.method == 'POST':
        # 接受的数据格式{"name":"",...}
        user_data = request.get_json()
        # print(user_data)
        name = user_data.get("name")
        phone = user_data.get("phone")
        password = user_data.get("password")
        password2 = user_data.get("password2")
        info = ""
        if not all([name, password, password2, phone]):
            return jsonify({'code': 1, "error": "参数不完整"})
        elif not re.match("\w{6,18}", name):
            return jsonify({'code': 1, "error": "用户名输入不合法，请重新输入"})
        elif password != password2:
            return jsonify({'code': 1, "error": "两次密码不一致"})
        try:
            user = User.query.filter_by(name=name).first()
        except:
            return jsonify({"code": 2, 'msg': '数据库查询错误'})
        if user:
            return jsonify({"code": 1, 'msg': '用户已存在'})
        try:
            user = User(name, password, phone)
            db.session.add(user)
            db.session.commit()
        except:
            db.session.rollback()
            return jsonify({'code': 2, 'msg': "数据库错误"})
        return jsonify({'code': 0, 'msg': "注册成功"})

# 手机登录
def login_by_phone():
    req_data=request.get_json()
    phone=req_data.get("phone")
    password=req_data.get("password")
    if not all([phone,password]):
        current_app.logger.error(RET.PARAMERR.msg)
        return jsonify(code=RET.PARAMERR.code,msg=RET.PARAMERR.msg)
    keys=["id","phone","scope"]
    filters={
        User.phone==phone,
        User.role_id==Role.id
    }
    field=[User.id,User.phone,Role.role]
    user=DBQuery.get_one_use_field(keys=keys,field=field,filters=filters)
    if user:
        user_id=user.get("id")
        scope=user.get("scope")
        token = generate_token(user_id, scope)
        expiration=current_app.config["TOKEN_EXPIRATION"]
        name=current_app.config["REDIS_PREFIX"]+str(user.id)+"_"+str(uuid)
        token_cache=token_cache.set_token(token=token,token_name=name,expiration=expiration)
        if token_cache:
            return jsonify(RET.Success.json_msg(data=token))
        else:
            return jsonify(RET.LoginFailed.json_msg())

#邮箱登录
def login_by_email():
    req_data=request.get_json()
    email=req_data.get("email")
    password=req_data.get("password")
    if not all([email,password]):
        current_app.logger.error(RET.PARAMERR.msg)
        return jsonify(code=RET.PARAMERR.code,msg=RET.PARAMERR.msg)
    keys=["id","email","scope"]
    filters={
        User.email==email,
        User.role_id==Role.id
    }
    field=[User.id,User.email,Role.role]
    user=DBQuery.get_one_use_field(keys=keys,field=field,filters=filters)
    if user:
        user_id=user.get("id")
        scope=user.get("scope")
        token = generate_token(user_id, scope)
        expiration=current_app.config["TOKEN_EXPIRATION"]
        name=current_app.config["REDIS_PREFIX"]+str(user.id)+"_"+str(uuid)
        token_cache=token_cache.set_token(token=token,token_name=name,expiration=expiration)
        if token_cache:
            return jsonify(RET.Success.json_msg(data=token))
        else:
            return jsonify(RET.LoginFailed.json_msg())


#--------------------------用户信息----------------------------------------
def get_user_info():
    filters={
        User.id==g.user_id
    }
    user=UserDB.get_one(filters)
    if user:
        return jsonify(RET.Success.json_msg(data=user))

# 注销登录
def logout():
    user_id = g.user_id
    uuid = g.uuid
    name = current_app.config["REDIS_PREFIX"] + str(user_id) + "_" + str(uuid)
    token_cache.del_token(name)
    return jsonify(code=RET.OK,data="success",message="注销成功")

